from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.db import models
from django.utils import timezone

from utils.exceptions import CustomError


# Create your models here.

class UserManager(BaseUserManager):
    def create_user(self, username, password=None, **extra_fields):
        if username is None:
            raise CustomError("请输入手机号！")
        user = self.model(username=username, is_superuser=False, last_login=timezone.now(), **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, **extra_fields):
        user = self.create_user(username, password, **extra_fields)
        user.is_superuser = True
        user.is_staff = True
        user.save(using=self._db)
        return user


class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(verbose_name='账号', max_length=30, unique=True,
                                db_index=True)  # db_index=True 则代表着为此字段设置索引。
    nickname = models.CharField(verbose_name='昵称', max_length=100, null=True, blank=True)
    is_active = models.BooleanField(verbose_name='用户状态', default=True)
    is_staff = models.BooleanField(verbose_name='是否是管理员', default=False)
    create_time = models.DateTimeField(verbose_name='注册时间', auto_now_add=True,
                                       editable=False)  # 如果为False，则该字段将不会显示在admin或其他ModelForm。在模型验证期间也将跳过它们

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    def __unicode__(self):
        return self.nickname or self.username

    def is_member(self):
        if self.is_superuser or self.is_staff:
            return False
        return True

    class Meta:
        db_table = "auth_user"
        verbose_name = "账号"
        ordering = ['-create_time']
